﻿using System;
using System.Linq;
using System.Web.Mvc;
using MiniWeb.Core.Entities;
using MiniWeb.Task;
using MiniWeb.Web.Controllers.Admin.ProductsTypeManager.ViewModels;
using WFramework.Mappers;
using WFramework.MvcPager;
using WFramework;
using System.Collections.Generic;
namespace MiniWeb.Web.Controllers.Admin.ProductsTypeManager
{

    public class ProductsTypeManagerController : BaseController
    {
        private readonly ProductsTypeTask _productstypeTask = new ProductsTypeTask();

        public ActionResult List(int pageIndex = 1, int pageSize = 20)
        {
            var pagedList = _productstypeTask.GetPagedList(pageIndex, pageSize);

            var model = new PagedList<ProductsType>(pagedList.ToList(), pageIndex, pageSize, pagedList.TotalItemCount);

            return View(model);
        }


        public ActionResult Save(int? id)
        {
            var model = new SaveProductsType();
            model.Sort = 1;
            if (id != null)
            {
                var item = _productstypeTask.GetById((int)id);
                if (item == null)
                    return AlertMsg("参数错误", HttpContext.Request.UrlReferrer.PathAndQuery);

                model = EntityMapper.Map<ProductsType, SaveProductsType>(item);
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Save(SaveProductsType savemodel)
        {

            if (ModelState.IsValid)
            {

                if (savemodel.ID == null)
                {
                    var model = new ProductsType
                                    {
                                        TypeName = savemodel.TypeName,
                                        CreateDate = DateTime.Now,
                                        Sort = savemodel.Sort,
                                    };
                    _productstypeTask.Add(model);
                }
                else
                {
                    var model = _productstypeTask.GetById((int)savemodel.ID);

                    if (model == null)
                        return AlertMsg("参数错误", HttpContext.Request.UrlReferrer.PathAndQuery);
                    model.Sort = savemodel.Sort;
                    model.TypeName = savemodel.TypeName;
                   
                    _productstypeTask.Update(model);
                }
                return AlertMsg("保存成功", HttpContext.Request.UrlReferrer.PathAndQuery);

            }

            return View(savemodel);
        }



        #region 删除用户信息 Delete

        [HttpPost]
        public void Delete(int id)
        {
            _productstypeTask.Delete(id);
        }

        #endregion
    }
}